// Copyright(C) Japan Android Group Gunma
// LGPL License
// Writers Rabbit-U

package jp.android_group.gunma.gunma_app_lib;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Xml;

public class LocationGetter {

	static public class LocationInfo {
		public Location m_location;
		public String m_country;
		public String m_prefecture;
		public String m_city;
		public String m_town;
	}
	
	public interface GetLocationListener {
		
		void onGetLocation(LocationInfo info);
		void onError();
		
	}
	
	Context m_context;
	
	LocationManager m_lm;

	LocationInfo getLocationInfo(Location location) {

		String strUri = "http://www.finds.jp/ws/rgeocode.php";
		
		strUri += "?lat=" + location.getLatitude() + "&lon=" + location.getLongitude();
		
		URI uri = URI.create(strUri);
		HttpClient client = new DefaultHttpClient();
	    
	    XmlPullParser parser = Xml.newPullParser();
        HashMap<String, String> map = new HashMap<String, String>();
	    
        HttpGet getMethod = new HttpGet(uri);  
        HttpResponse response;
		try {
			response = client.execute(getMethod);
		} catch (ClientProtocolException e) {
			return null;
		} catch (IOException e) {
			return null;
		}
		
        if(response.getStatusLine().getStatusCode() != 200 ) {
        	return null;
        }
        	
		HttpEntity entity = response.getEntity();

    	InputStream is;
    	
		try {
			is = entity.getContent();
		} catch (IllegalStateException e) {
			return null;
		} catch (IOException e) {
			return null;
		}  
		
        InputStreamReader isr = new InputStreamReader(is);
        
        try {
			parser.setInput(isr);
		} catch (XmlPullParserException e) {
			return null;
		}
		
        int eventType;
		try {
			eventType = parser.getEventType();
		} catch (XmlPullParserException e) {
			return null;
		}
		
        String name = "";
        String text;
        
        while(eventType != XmlPullParser.END_DOCUMENT) {
        
        	switch(eventType) {
        	case XmlPullParser.START_TAG:
        		name = parser.getName();
        		break;
        	case XmlPullParser.END_TAG:
        		name = "";
        		break;
        	case XmlPullParser.TEXT:
        		text = parser.getText();
        		map.put(name, text);
        		break;
        	}
        	
        	try {
				eventType = parser.next();
			} catch (XmlPullParserException e) {
				return null;
			} catch (IOException e) {
				return null;
			}
			
        }
        
        try {
			is.close();
		} catch (IOException e) {
			// do nothing.
		}
		
		LocationInfo info = new LocationInfo();
		info.m_location = location;
//		info.m_country = country;
		info.m_prefecture = map.get("pname");
		info.m_city = map.get("mname");
		info.m_town = map.get("section");
		
		return info;

	}
	
	LocationListener m_listenerLocation = new LocationListener() {

		public void onLocationChanged(Location location) {
			m_lm.removeUpdates(this);
			LocationInfo info = getLocationInfo(location);
			if( info == null ) {
				m_listenerGet.onError();
			} else {
				m_listenerGet.onGetLocation(info);
			}
		}

		public void onProviderDisabled(String provider) {
			// do nothing.
		}

		public void onProviderEnabled(String provider) {
			// do nothing.
		}

		public void onStatusChanged(String provider, int status,
				Bundle extras) {
			// do nothing.
		}
    	
    };
    
    GetLocationListener m_listenerGet;

	public void startGetLocation(Context context, GetLocationListener listener) {

		m_context = context;
		m_listenerGet = listener;
		
		{
	        m_lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
	        String provider = getLocationProvider(context);
	        if( provider == null ) {
	        	m_listenerGet.onError();
	        	return;
	        }
			m_lm.requestLocationUpdates(provider, 0, 0.0f, m_listenerLocation);
		}
		
	}
	
	public void cancel(){
		m_lm.removeUpdates(m_listenerLocation);
	}
	
	
	public static String getLocationProvider(Context context) {

		String provider = null;

		{
			ContentResolver resolver = context.getContentResolver();
			Uri uri = Uri
					.parse("content://RabiSoft.CommonSettings.SettingsProvider/LocationProvider");
			Cursor cursor = resolver.query(uri, null, null, null, null);
			if (cursor != null) {
				cursor.moveToFirst();
				int index_provider = cursor
						.getColumnIndexOrThrow("provider");
				provider = cursor.getString(index_provider);
				cursor.close();
			}
		}

		if( provider == null ) {
			LocationManager manager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
			if( manager.isProviderEnabled(LocationManager.GPS_PROVIDER) ) {
				provider = LocationManager.GPS_PROVIDER;
			} else if( manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) ) {
				provider = LocationManager.NETWORK_PROVIDER;
			}
		}

		return provider;

	}
	
}
